import { taiLogin, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      memberId: '',
      roles: [],
      permissions: [],
      isApartment: false,
      apartment: {}
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const params = {
          password: userInfo.password,
          code: userInfo.code,
          uuid: userInfo.uuid
        }
        if (/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(username)) {
          params.phonenumber = username
        } else if (/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(username)) {
          params.email = username
        }
        return new Promise((resolve, reject) => {
          taiLogin(params).then(res => {
            let data = res.data
            setToken(data.access_token)
            this.token = data.access_token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            const avatar = (user.avatar == "" || user.avatar == null) ? defAva : user.avatar;

            if (user.authCodeList && user.authCodeList.length > 0) { // 验证返回的roles是否是一个非空数组
              // this.roles = res.roles
              // this.permissions = res.permissions
              this.permissions = user.authCodeList
            } else {
              this.permissions = ["no"]
            }
            this.id = user.userId
            this.name = user.userName
            this.avatar = avatar
            this.memberId = user.memberId
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            this.id = null
            this.memberId = null
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 设置是否创建公寓
      setApartment(value, boolean) {
        this.apartment = value
        this.isApartment = boolean
      }
    }
  })

export default useUserStore
